<?php
/**
 * 平台销量 (平台基础销量数据（日、月）)
 */
namespace App\Logic\SalesAmazon;

use App\Models\Amazon\AmazonOrder;
use App\Models\Basics\AmazonCountry;
use App\Models\Basics\SysPlat;
use App\Models\Basics\SysPlatCountry;
use App\Models\Product\ProductAmazonSku;
use App\Models\Product\ProductAmazonSkuCCS;
use App\Models\Product\ProductRakutenSku;
use App\Models\Product\ProductSku;
use App\Models\Rakuten\RakutenOrder;
use App\Models\SalesAmazon\SalesVolumeDay;
use App\Models\SalesAmazon\SalesVolumeMonth;
use App\Models\Shopify\ShopifyOrder;
use Illuminate\Support\Facades\DB;
class SalesVolume
{
    /**
     * 统计各平台订单销量到erp (erp基础销量表(SalesVolumeDay))
     * @param int $days
     */
    public static function initPlatform($days = 1)
    {
        $amazonPlat = SysPlat::PLAT_AMAZON; //amazon平台
        $shopifyPlat = SysPlat::PLAT_SHOPIFY; //shopify平台
        $rakutenPlat = SysPlat::PLAT_RAKUTEN; //rakuten平台

        $i = 1;
        while(true) {
            if ($i > $days) break;
            $time = strtotime("-{$i} days");
            $start = date('Y-m-d 00:00:00', $time);
            $end = date('Y-m-d 23:59:59', $time);
            $day = date('Ymd', $time);

            try {
                DB::beginTransaction();

                //1.amazon订单（日销量）
                SalesVolumeDay::query()->where('plat_id', $amazonPlat)->where('day', $day)->update(['volume' => 0]);
                $countrys = [];
                $sku = [];
                $skuClassify = [];
                AmazonOrder::query()
                    ->where('purchase_date', '>=', $start)
                    ->where('purchase_date', '<=', $end)
                    ->select('id', 'amazon_order_id', 'marketplace_id')
                    ->orderBy('id')
                    ->chunk(500, function ($aOrders) use (&$countrys, &$sku, &$skuClassify, $day, $amazonPlat) {
                        foreach ($aOrders as $aOrder) {
                            if (!array_key_exists($aOrder->marketplace_id, $countrys)) {
                                $countrys[$aOrder->marketplace_id] = AmazonCountry::getCountryIdByMarketplaceId($aOrder->marketplace_id);
                            }
                            $countryId = $countrys[$aOrder->marketplace_id];
                            foreach ($aOrder->items as $item) {
                                $volume = SalesVolumeDay::query()
                                    ->where('plat_id', $amazonPlat)
                                    ->where('country_id', $countryId)
                                    ->where('seller_sku', $item->sku)
                                    ->where('day', $day)
                                    ->first();

                                if (!$volume) {
                                    //产品sku
                                    if (!array_key_exists($item->sku, $sku)) {
                                        $platSkuId = ProductAmazonSku::query()->where('seller_sku', $item->sku)->value('psku_id');
                                        if (!$platSkuId) {
                                            //截取平台sku,用于非正常途径匹配skuId (平台sku未正常录入/匹配异常时使用，例如非正常平台sku：amzn.gr.AM04205-AMDE-FBA100-UbYwlFM_A-VG、)
                                            $pskuCode = substr($item->sku, (stripos($item->sku, 'AM0')),7);
                                            if ($pskuCode) {
                                                $platSkuId = ProductSku::getValueByCode($pskuCode,'id'); //skuId
                                            }
                                        }
                                        $sku[$item->sku] = $platSkuId ?: 0;
                                    }
                                    $pSkuId = $sku[$item->sku] ?? 0;

                                    //产品品类
                                    if (!array_key_exists($pSkuId, $skuClassify)) {
                                        $_classifyId = ProductSku::getValueById($pSkuId, 'classify_id');
                                        $skuClassify[$pSkuId] = $_classifyId ?: 0;
                                    }
                                    $classifyId = $skuClassify[$pSkuId] ?? 0;

                                    SalesVolumeDay::query()->create([
                                        'plat_id' => $amazonPlat,
                                        'country_id' => $countryId,
                                        'seller_sku' => $item->sku,
                                        'day' => $day,
                                        'classify_id' => $classifyId,
                                        'psku_id' => $pSkuId,
                                        'volume' => $item->quantity,
                                    ]);
                                } else {
                                    $volume->volume += $item->quantity;
                                    $volume->save();
                                }
                            }
                        }
                    });
                sleep(2);

                //2.shopify订单（日销量）
                SalesVolumeDay::query()->where('plat_id', $shopifyPlat)->where('day', $day)->update(['volume' => 0]);
                $shopifyCountryId = 1; //US
                $shopifySku = [];
                $shopifySkuClassify = [];
                ShopifyOrder::query()
                    ->where('purchase_at', '>=', strtotime($start))
                    ->where('purchase_at', '<=', strtotime($end))
                    ->orderBy('id')
                    ->chunk(500, function ($aOrders) use (&$shopifyCountryId, &$shopifySku, &$shopifySkuClassify, $day, $shopifyPlat) {
                        foreach ($aOrders as $aOrder) {
                            foreach ($aOrder->shopify_orders_items as $item) {
                                $volume = SalesVolumeDay::query()
                                    ->where('plat_id', $shopifyPlat)
                                    ->where('country_id', $shopifyCountryId)
                                    ->where('seller_sku', $item->sku)
                                    ->where('day', $day)
                                    ->first();
                                if (!$volume) {
                                    //产品sku
                                    if (!array_key_exists($item->sku, $shopifySku)) {
                                        //$platSkuId = ProductShopifySku::query()->where('seller_sku', $item->sku)->value('psku_id');
                                        $platSkuId = ProductSku::query()->where('psku_code', $item->sku)->value('id');
                                        $shopifySku[$item->sku] = $platSkuId ?: 0; //skuId
                                    }
                                    $pSkuId = $shopifySku[$item->sku] ?? 0;

                                    //产品品类
                                    if (!array_key_exists($pSkuId, $shopifySkuClassify)) {
                                        $_classifyId = ProductSku::getValueById($pSkuId, 'classify_id');
                                        $shopifySkuClassify[$pSkuId] = $_classifyId ?: 0;
                                    }
                                    $classifyId = $shopifySkuClassify[$pSkuId] ?? 0;

                                    SalesVolumeDay::query()->create([
                                        'plat_id' => $shopifyPlat,
                                        'country_id' => $shopifyCountryId,
                                        'seller_sku' => $item->sku,
                                        'day' => $day,
                                        'classify_id' => $classifyId,
                                        'psku_id' => $pSkuId,
                                        'volume' => $item->quantity,
                                    ]);
                                } else {
                                    $volume->volume += $item->quantity;
                                    $volume->save();
                                }
                            }
                        }
                    });
                sleep(2);

                //3.rakuten订单（日销量）
                SalesVolumeDay::query()->where('plat_id', $rakutenPlat)->where('day', $day)->update(['volume' => 0]);
                $rakutenCountryId = 12; //JP国家
                $rakutenSku = [];
                $rakutenSkuClassify = [];
                RakutenOrder::query()
                    ->where('order_datetime', '>=', strtotime($start))
                    ->where('order_datetime', '<=', strtotime($end))
                    ->orderBy('id')
                    ->chunk(500, function ($rOrders) use (&$rakutenCountryId, &$rakutenSku, &$rakutenSkuClassify, $day, $rakutenPlat) {
                        foreach ($rOrders as $rOrder) {
                            foreach ($rOrder->rakuten_orders_items as $rakutenItem) {
                                $volume = SalesVolumeDay::query()
                                    ->where('plat_id', $rakutenPlat)
                                    ->where('country_id', $rakutenCountryId)
                                    ->where('seller_sku', $rakutenItem->platform_sku)
                                    ->where('day', $day)
                                    ->first();
                                if (!$volume) {
                                    //产品sku
                                    if (!array_key_exists($rakutenItem->platform_sku, $rakutenSku)) {
                                        $platSkuId = ProductRakutenSku::query()->where('seller_sku', $rakutenItem->platform_sku)->value('psku_id');
                                        $rakutenSku[$rakutenItem->platform_sku] = $platSkuId ?: 0; //skuId
                                    }
                                    $pSkuId = $rakutenSku[$rakutenItem->platform_sku] ?? 0;

                                    //产品品类
                                    if (!array_key_exists($pSkuId, $rakutenSkuClassify)) {
                                        $_classifyId = ProductSku::getValueById($pSkuId, 'classify_id');
                                        $rakutenSkuClassify[$pSkuId] = $_classifyId ?: 0;
                                    }
                                    $classifyId = $rakutenSkuClassify[$pSkuId] ?? 0;

                                    SalesVolumeDay::query()->create([
                                        'plat_id' => $rakutenPlat,
                                        'country_id' => $rakutenCountryId,
                                        'seller_sku' => $rakutenItem->platform_sku,
                                        'day' => $day,
                                        'classify_id' => $classifyId,
                                        'psku_id' => $pSkuId,
                                        'volume' => $rakutenItem->units,
                                    ]);
                                } else {
                                    $volume->volume += $rakutenItem->units;
                                    $volume->save();
                                }
                            }
                        }
                    });
                sleep(2);

                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                report($e);
            }

            echo $day.PHP_EOL;
            $i++;
            sleep(1);
        }
    }

    /**
     * 补录数据
     * @param $startDate
     * @param $endDate
     * @return false
     */
    public static function initPlatformBack($startDate, $endDate)
    {
        $amazonPlat = SysPlat::PLAT_AMAZON;

        $startDates = $startDate == 'null' ? date('Y-m-d', strtotime("-1 days")) : $startDate; //开始时间
        $endDates = $endDate == 'null' ? date('Y-m-d', strtotime("-1 days")) : $endDate; //结束时间
        if (!strtotime($startDates) || !strtotime($endDates)) return false;


        $bof = strtotime($startDates); //开始
        $eof = strtotime($endDates); //结束
        while(true) {
            if ($bof > $eof) break;
            $time = $bof;
            $start = date('Y-m-d 00:00:00', $time);
            $end = date('Y-m-d 23:59:59', $time);
            $day = date('Ymd', $time);
            DB::beginTransaction();
            try {
               /* //1.amazon订单（日销量）
                SalesVolumeDay::query()->where('plat_id', $amazonPlat)->where('day', $day)->update(['volume' => 0]);
                $countrys = [];
                $sku = [];
                $skuClassify = [];
                AmazonOrder::query()
                    ->where('purchase_date', '>=', $start)
                    ->where('purchase_date', '<=', $end)
                    ->select('id', 'amazon_order_id', 'marketplace_id')
                    ->orderBy('id')
                    ->chunk(500, function ($aOrders) use (&$countrys, &$sku, &$skuClassify, $day, $amazonPlat) {
                        foreach ($aOrders as $aOrder) {
                            if (!array_key_exists($aOrder->marketplace_id, $countrys)) {
                                $countrys[$aOrder->marketplace_id] = AmazonCountry::getCountryIdByMarketplaceId($aOrder->marketplace_id);
                            }
                            $countryId = $countrys[$aOrder->marketplace_id];
                            foreach ($aOrder->items as $item) {
                                $volume = SalesVolumeDay::query()
                                    ->where('plat_id', $amazonPlat)
                                    ->where('country_id', $countryId)
                                    ->where('seller_sku', $item->sku)
                                    ->where('day', $day)
                                    ->first();
                                if (!$volume) {
                                    //产品sku
                                    if (!array_key_exists($item->sku, $sku)) {
                                        $platSkuId = ProductAmazonSku::query()->where('seller_sku', $item->sku)->value('psku_id');
                                        if (!$platSkuId) {
                                            //截取平台sku,用于非正常途径匹配skuId (平台sku未正常录入/匹配异常时使用，例如非正常平台sku：amzn.gr.AM04205-AMDE-FBA100-UbYwlFM_A-VG、)
                                            $pskuCode = substr($item->sku, (stripos($item->sku, 'AM0')),7);
                                            if ($pskuCode) {
                                                $platSkuId = ProductSku::getValueByCode($pskuCode,'id'); //skuId
                                            }
                                        }
                                        $sku[$item->sku] = $platSkuId ?: 0;
                                    }
                                    $pSkuId = $sku[$item->sku] ?? 0;

                                    //产品品类
                                    if (!array_key_exists($pSkuId, $skuClassify)) {
                                        $_classifyId = ProductSku::getValueById($pSkuId, 'classify_id');
                                        $skuClassify[$pSkuId] = $_classifyId ?: 0;
                                    }
                                    $classifyId = $skuClassify[$pSkuId] ?? 0;

                                    SalesVolumeDay::query()->create([
                                        'plat_id' => $amazonPlat,
                                        'country_id' => $countryId,
                                        'seller_sku' => $item->sku,
                                        'day' => $day,
                                        'psku_id' => $pSkuId,
                                        'classify_id' => $classifyId,
                                        'volume' => $item->quantity,
                                    ]);
                                } else {
                                    $volume->volume += $item->quantity;
                                    $volume->save();
                                }
                            }
                        }
                    });
                sleep(2);*/

                //二.平台月销量(月份)
                $_start = date('Ym01', $time);
                $_end = date('Ymd', $time);
                $date = date('Ym', $time);
                $classify = [];
                $seller = [];
                $volumeMonth = SalesVolumeDay::query()
                    ->where('plat_id', $amazonPlat)
                    ->whereBetween('day', [$_start, $_end])
                    ->select('plat_id', 'country_id', 'seller_sku', 'psku_id', DB::raw('sum(volume) as volume'))
                    ->groupBy(['plat_id', 'country_id', 'seller_sku'])
                    ->get();

                foreach ($volumeMonth as $item) {
                    $model = SalesVolumeMonth::query()
                        ->where('plat_id', $item->plat_id)
                        ->where('country_id', $item->country_id)
                        ->where('seller_sku', $item->seller_sku)
                        ->where('month', $date)
                        ->first();
                    if ($model) {
                        $model->volume = $item->volume;
                        $model->save();
                    }else {

                        $pSkuId = $item->psku_id;

                        //产品品类
                        if (!array_key_exists($pSkuId, $classify)) {
                            $_classifyId = ProductSku::getValueById($pSkuId, 'classify_id');
                            $classify[$pSkuId] = $_classifyId ?? 0;
                        }
                        $classifyId = $classify[$pSkuId];
                        if (!$classifyId) continue;

                        //amazon销售人员
                        if ($item->plat_id == $amazonPlat) {
                            if (!array_key_exists($classifyId, $seller)) {
                                $seller[$classifyId] = ProductAmazonSkuCCS::getSellerId($item->country_id, $classifyId);
                            }
                        }
                        $sellerId = $seller[$classifyId] ?? 0;

                        SalesVolumeMonth::query()->create([
                            'plat_id' => $item->plat_id,
                            'country_id' => $item->country_id,
                            'seller_sku' => $item->seller_sku,
                            'month' => $date,
                            'classify_id' => $classifyId,
                            'seller_id' => $sellerId,
                            'volume' => $item->volume,
                        ]);
                    }
                }
                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                report($e);
            }

            echo $day.PHP_EOL;
            $bof += 60*60*24;

            sleep(2);
        }
    }

}
